package com.zyg.config;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * AOP打印日志
 */
@Aspect
@Component
@Order(-5)
@Slf4j
public class SystemLogAspect {
    /***
     * 拦截控制层的操作日志
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(public * com.zyg..controller..*.*(..))") //"controllerAspect()"
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = null ;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //打印请求内容
        log.info("===============接收到请求===============");
        log.info("url={}",request.getRequestURI());
        //method
        log.info("method={}",request.getMethod());
        //ip
        log.info("ip={}",request.getRemoteAddr());
        //类方法
        log.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+
                "."+joinPoint.getSignature().getName());
        //参数
        log.info("args={}", Arrays.toString(joinPoint.getArgs()));

        long startTime = System.currentTimeMillis();
        proceed = joinPoint.proceed();
        String msg = JSON.toJSONString(proceed);
        long endTime = System.currentTimeMillis();

        long diff = endTime - startTime;

        log.info("=====>响应结果为：{}", msg);
        log.info("=====>处理本次请求共耗时：{} ms",diff);
        log.info("===============结束本次请求===============");

        return proceed ;
    }
}
